class Zerocms::ZerocmsController < ActionController::Base
	add_flash_types :warning
  add_flash_types :error
  add_flash_types :notice
  add_flash_types :info

  include Zerocms::ZerocmsHelper
  include Zerocms::SessionHelper
  include Zerocms::SiteHelper
  include Zerocms::HtmlHelper
  include Zerocms::UserRolesHelper
  include Zerocms::ShortCodeHelper
  include Zerocms::PluginsHelper
  include Zerocms::ThemeHelper
  include Zerocms::HooksHelper
  include Zerocms::ContentHelper
  include Zerocms::CaptchaHelper
  include Zerocms::UploaderHelper

  PluginRoutes.all_helpers.each{|h| include h.constantize }

	before_action :zerocms_site_check_existence, except: [:render_error, :captcha]
  before_action :zerocms_before_actions, except: [:render_error, :captcha]
  after_action :zerocms_after_actions, except: [:render_error, :captcha]
  protect_from_forgery with: :exception

  layout Proc.new { |controller| controller.request.xhr? ? false : 'default' }
  helper_method :current_user

    # show page error
  def render_error(status = 404, exception = nil, message = "")
    Rails.logger.debug "Zerocms - 404 url: #{request.original_url rescue nil} ==> message: #{exception.message if exception.present?} ==> #{params[:error_msg]} ==> #{caller.inspect}"
    @message = "#{message} #{params[:error_msg] || (exception.present? ? "#{exception.message}<br><br>#{caller.inspect}" : "")}"
    @message = "" if Rails.env == "production"
    render "zerocms/#{status}", :status => status
  end

  private
  def zerocms_before_actions
    # including all helpers (system, themes, plugins) for this site
    # PluginRoutes.enabled_apps(current_site, current_theme.slug).each{|plugin| plugin_load_helpers(plugin) }

    # initializing short codes
    shortcodes_init()

    # initializing before and after contents
    zerocms_html_helpers_init

    # initializing before and after contents
    zerocms_content_init

    @_hooks_skip = []
    # trigger all hooks before_load_app
    hooks_run("app_before_load")

    request.env.except!('HTTP_X_FORWARDED_HOST') if request.env['HTTP_X_FORWARDED_HOST'] # just drop the variable

    views_dir = "app/apps/"
    self.prepend_view_path(File.join($zerocms_engine_dir, views_dir).to_s)
    self.prepend_view_path(Rails.root.join(views_dir).to_s)

    Zerocms::PostDefault.current_user = zerocms_current_user
    Zerocms::PostDefault.current_site = current_site
  end

  # initialize ability for current user
  def current_ability
    @current_ability ||= Zerocms::Ability.new(zerocms_current_user, current_site)
  end

  def zerocms_after_actions
    # trigger all actions app after load
    hooks_run("app_after_load")
  end

  # redirect to sessions login form when the session was expired.
  def auth_session_error
    redirect_to zerocms_root_path
  end

  # check if current site exist, if not, this will be redirected to main domain
  # Also, check current site status
  def zerocms_site_check_existence()
    if !current_site.present?
      if Zerocms::Site.main_site.present?
        redirect_to Zerocms::Site.main_site.decorate.the_url
      else
        redirect_to zerocms_admin_installers_path
      end
    elsif (zerocms_current_user.present? && !zerocms_current_user.admin?) || !zerocms_current_user.present?
      # inactive page control
      if current_site.is_inactive?
        p = current_site.posts.find(current_site.get_option('page_inactive')).decorate
        redirect_to(p.the_url) if params != {"controller"=>"zerocms/frontend", "action"=>"post", "slug"=>p.the_slug}
      end

      # maintenance page and IP's control
      if current_site.is_maintenance? && !current_site.get_option('maintenance_ips', '').split(',').include?(request.remote_ip)
        p = current_site.posts.find(current_site.get_option('page_maintenance')).decorate
        redirect_to(p.the_url) if params != {"controller"=>"zerocms/frontend", "action"=>"post", "slug"=>p.the_slug}
      end
    end
  end

  def current_user
    zerocms_current_user
  end
end
